<template>
  <div class="table-container">
    <byui-query-form>
      <byui-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary" @click="handleAdd"
          >添加</el-button
        >
        <el-button icon="el-icon-delete" type="danger" @click="handleDelete"
          >删除</el-button
        >
      </byui-query-form-left-panel>
      <byui-query-form-right-panel>
        <el-form
          ref="form"
          :model="queryForm"
          :inline="true"
          @submit.native.prevent
        >
          <el-form-item label="查询类型">
            <el-select
              v-model="queryForm.type"
              placeholder="查询类型"
              style="width: 100px;"
            >
              <el-option label="ID" value="id"></el-option>
              <el-option label="用户名" value="username"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input v-model="queryForm.q" placeholder="请输入查询内容" />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              native-type="submit"
              @click="handleQuery"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </byui-query-form-right-panel>
    </byui-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      @selection-change="setSelectRows"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="ID" width="95" prop="id"></el-table-column>
      <el-table-column
        label="团队"
        prop="parentName"
        v-if="checkPermission(['root'])"
        width="200"
      ></el-table-column>
      <el-table-column
        label="账号"
        prop="username"
        width="200"
      ></el-table-column>
      <el-table-column label="头像" prop="avatar" width="70">
        <template slot-scope="scope">
          <div style="width: 60px; height: 60px; margin: auto;">
            <el-image
              :src="scope.row.avatar"
              style="width: 60px; height: 60px;"
            ></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联盟账号" prop="useUnion"></el-table-column>
      <el-table-column label="余额" prop="money"></el-table-column>
      <el-table-column
        label="注册时间"
        prop="addtime"
        :formatter="formatDate"
      ></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="success"
            size="mini"
            @click="showAchievement(scope.row)"
            >查业绩</el-button
          >
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="primary" size="mini" @click="open(scope.row)"
            >绑定pid</el-button
          >
          <el-button type="warning" size="mini" @click="tableDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
    <edit ref="edit" @msgEvent="saveUser" :unionList="unionList"></edit>
    <el-dialog
      :title="achievement.title"
      :visible.sync="isShowAchievement"
      width="450px"
      center
    >
      <el-date-picker
        v-model="achievement.from.time"
        type="datetimerange"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        align="right"
        @change="clickAchievement"
      ></el-date-picker>
      <div
        style="
          margin: 20px auto;
          font-size: 16px;
          line-height: 40px;
          text-align: center;
        "
      >
        总收益：
        <span
          style="
            margin: 20px auto;
            color: #ff430d;
            font-weight: bold;
            font-size: 20px;
          "
          >{{ achievement.money }}</span
        >
        元
      </div>
    </el-dialog>
    <el-dialog title="配置PID" :visible.sync="pidshow" width="900px" center>
      <div style="display: flex;">
        <el-cascader
          style="width: 600px; margin-bottom: 10px;"
          v-model="valuess"
          :options="options"
          @expand-change="showchange"
          @change="handleChange"
        ></el-cascader>
        <div style="margin-left: 10px;">
          <el-button icon="el-icon-plus" type="primary" @click="dosure"
            >添加</el-button
          >
        </div>
      </div>
      <el-table :data="banglist" style="width: 100%;">
        <el-table-column prop="name" label="联盟账号" width="180">
        </el-table-column>
        <el-table-column prop="session" label="媒体" width="180">
        </el-table-column>
        <el-table-column prop="parentId" label="PID" width="400">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="delList(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import checkPermission from "@/utils/permission";
import {
  listUsers,
  delUser,
  addUser,
  listUnionName,
  listUnionChannel,
  userAchievement,
  bindPid,
  delPid,
  getPid,
} from "@/api/index";
import Edit from "./components/edit";

export default {
  name: "Table",
  components: {
    Edit,
  },
  filters: {},
  data() {
    return {
      valuess: [],
      banglist: [],
      options: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date(new Date().toLocaleDateString());
              var start = new Date();
              start.setTime(
                new Date(start.toLocaleDateString()).getTime() -
                  24 * 60 * 60 * 1000
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本周",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().toLocaleDateString());
              var weekday = start.getDay();
              start.setDate(start.getDate() - weekday + 1);
              //start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本月",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().toLocaleDateString());
              start.setDate(1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上月",
            onClick(picker) {
              const end = new Date();
              const start = new Date(
                new Date().getFullYear(),
                new Date().getMonth() - 1,
                1
              );
              var day = new Date(
                end.getFullYear(),
                end.getMonth(),
                0
              ).getDate();
              end.setTime(
                new Date(
                  new Date().getFullYear(),
                  new Date().getMonth() - 1,
                  day,
                  23,
                  59,
                  59
                )
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pidshow: false,
      isShowAchievement: false,
      achievement: {
        title: "",
        from: {
          time: [new Date(new Date().toLocaleDateString()), new Date()],
          uid: "",
        },
        money: 0,
      },
      imgShow: true,
      list: [
        {
          addtime: "1596790040",
          avatar: "",
          id: "75",
          money: "0.00",
          parentId: "36",
          pid: "mm_927210126_1381700068_110744450154",
          remark: "",
          roles: "editor",
          useChannel: "1381700068",
          useUnion: "王猛188568",
          username: "二组杨蒙蒙",
        },
      ],
      listLoading: false,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        q: "",
        type: "",
      },
      unionList: [],
      rows: [],
      values: [],
      pid_id: "",
    };
  },
  watch: {
    // valuess(val) {
    //   console.log("000000", val);
    //   this.valuess = val;
    // },
  },
  created() {
    this.fetchData();
    if (this.checkPermission(["admin"])) {
      //   // 团队管理直接在此处获取;
      listUnionName({}).then((res) => {
        if (res.code && res.code === 200) {
          this.unionList = res.data;
          const nodes = [];
          for (const i in res.data) {
            const obj = {
              value: res.data[i],
              label: res.data[i],
              children: [],
            };
            nodes.push(obj);
          }
          // console.log(nodes);
          this.options = nodes;
          if (res.data.length == 0) {
            this.$baseAlert(
              "必须先添加淘宝账号才能添加用户和操作用户",
              "请先添加账号",
              () => {
                this.$router.push("/admin/unionTaobao");
              }
            );
          }
        }
      });
    }
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    // 确认添加
    dosure() {
      bindPid({
        user_id: this.rows.id,
        pid_id: this.pid_id,
      }).then((res) => {
        // console.log(res);
        this.getPid();
      });
    },
    // 删除pid
    delList(row) {
      this.$baseConfirm("你确定要删除吗", null, () => {
        delPid({
          user_id: this.rows.id,
          pid_id: row.id,
        })
          .then((res) => {
            console.log(res);
            this.getPid();
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    open(row) {
      console.log(row);
      this.rows = row;
      this.getPid();
      this.pidshow = true;
    },
    getPid() {
      getPid({ user_id: this.rows.id })
        .then((res) => {
          this.banglist = res.data;
          // console.log('gitpid',res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    showchange(value) {
      // console.log("showchange", value);
      listUnionChannel({ unionName: value[0] }).then((res) => {
        console.log(res);
        const nodes = [];
        this.pid_id = res.data.pid_id;
        for (const i in res.data.channel) {
          const obj = {
            value: res.data.channel[i].name,
            label: res.data.channel[i].name,
            leaf: false,
            children: [
              {
                value: res.data.channel[i].pid,
                label: res.data.channel[i].pid,
                leaf: true,
              },
            ],
          };
          nodes.push(obj);
        }
        for (const i in this.unionList) {
          if (this.unionList[i] == value[0]) {
            this.options[i].children = nodes;
          }
        }
        console.log(this.options);
      });
    },
    handleChange(value) {
      this.values = value;
      // console.log("----", this.valuess);
    },
    showAchievement(e) {
      this.isShowAchievement = true;
      this.achievement.title = e.username + "的业绩总览";
      this.achievement.from.uid = e.id;
      userAchievement(this.achievement.from).then((res) => {
        this.achievement.money = res.data;
      });
    },
    clickAchievement() {
      userAchievement(this.achievement.from).then((res) => {
        this.achievement.money = res.data;
      });
    },
    setSelectRows(val) {
      this.selectRows = val;
    },
    handleAdd() {
      this.$refs["edit"].showEdit();
    },
    handleEdit(row) {
      if (this.checkPermission(["root"]) && row.roles != "admin") {
        //root管理在此处获取
        listUnionName({
          parentId: row.parentId,
        }).then((res) => {
          if (res.code && res.code === 200) {
            this.unionList = res.data;
            if (res.data.length == 0) {
              this.$baseAlert(
                "该用户的团队管理未添加任何联盟账号，请提醒他添加账号",
                "请添加账号",
                () => {
                  //this.$router.push('/admin/unionTaobao');
                }
              );
            }
          }
        });
      }
      this.$refs["edit"].showEdit(row);
    },
    handleDelete() {
      if (this.selectRows.length === 0) {
        return this.$baseMessage("请至少选择一项", "error");
      }
      const ids = this.selectRows.map((item) => item.id).join();
      this.$baseConfirm("你确定要删除选中项吗", null, () => {
        delUser({
          id: ids,
        }).then((res) => {
          if (res.code && res.code === 200) {
            this.fetchData();
            this.$baseMessage(res.msg, "success");
          }
        });
      });
    },
    tableDelete(row) {
      this.$baseConfirm("你确定要删除" + row.username + "吗", null, () => {
        delUser({
          id: row.id,
        }).then((res) => {
          if (res.code && res.code === 200) {
            this.$baseMessage(res.msg, "success");
            this.fetchData();
          }
        });
      });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      listUsers(this.queryForm).then((res) => {
        this.list = res.data;
        this.total = res.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 500);
      });
    },
    formatDate(row, column) {
      let date = new Date(parseInt(row.addtime) * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1) + "-"
          : date.getMonth() + 1 + "-";
      let D =
        date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
      let h =
        date.getHours() < 10
          ? "0" + date.getHours() + ":"
          : date.getHours() + ":";
      let m =
        date.getMinutes() < 10
          ? "0" + date.getMinutes() + ":"
          : date.getMinutes() + ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    saveUser(e) {
      addUser(e).then((res) => {
        if (res.code && res.code === 200) {
          this.$baseMessage(res.msg, "success");
          this.$refs["edit"].close();
          this.fetchData();
        }
      });
    },
    checkPermission,
  },
};
</script>
<style lang="scss" scoped>
.items {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  padding: 5px;
  height: 30px;
  font-size: 14px;
  // line-height: 20px;
  border-bottom: 1px solid gray;

  .el-icon-delete {
    float: right;
    // display: none;
  }
}

.items:hover {
  background-color: #f2f2f2;

  .el-icon-delete {
    display: block;
  }
}
</style>
